package edu.chl.hajo.shop.core;

import edu.chl.hajo.shop.utils.AbstractDAO;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 * All customers
 *
 * @author hajo
 */
public class CustomerRegistry extends AbstractDAO<Customer, Long>
        implements ICustomerRegistry {

    // Factory method
    public static ICustomerRegistry newInstance(String pu) {
        return new CustomerRegistry(pu);
    }

    private CustomerRegistry(String name) {
        super(Customer.class,name);
    }

    @Override
  public List<Customer> getByName(String fname) {
     
         EntityManager em = super.getEM();

        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Customer> cq = cb.createQuery(Customer.class);
        Root<Customer> user = cq.from(Customer.class);

        cq.where(cb.equal(user.get(Customer_.fname), fname));

        List<Customer> result = null;
        try {
            result = em.createQuery(cq).getResultList();
        } catch (NoResultException e) {
            //this is fine, we will return null
        }
        em.close();

        return result;
        
    }
}
